<!--
  module - 用户与权限--- 组织

  @author mengft 2020-05-08
-->
<template>
  <div>
    <div class="search-bar">
      <div class="base-condition">
        <el-row justify="space-between">
          <el-col :span="12">
            <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal">
              <el-menu-item index="1">全部组织</el-menu-item>
            </el-menu>
          </el-col>
          <el-col :span="12" style="text-align:right;">
            <el-input
              v-model="listQuery.name"
              placeholder="请输入组织名称"
              class="radius-input"
              style="width: 200px;margin-top:7px;"
              @keyup.enter.native="search"
            >
              <i slot="prefix" class="el-input__icon el-icon-search" @click="search" /></el-input>
          </el-col>
        </el-row>
      </div>
    </div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>组织列表列表</span>
        <el-link type="primary" style="float: right; margin-left: 10px;" @click="handAdd()">添加</el-link>
      </div>
      <div>
        <el-row>
          <!-- start 列表 -->
          <el-table
            v-loading="listLoading"
            :data="list"
            style="width: 100%"
            :tree-props="{children: 'children', hasChildren: 'departmentId'}"
            row-key="departmentId"
            lazy
            :load="load"
            :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          >
            <el-table-column type="index" width="50" label="#" align="center" />
            <el-table-column label="组织名称" prop="name" :width="380" :show-overflow-tooltip="true" align="left" />
            <el-table-column label="排序" prop="sort" :width="180" :show-overflow-tooltip="true" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sort" autocomplete="off" placeholder="0-255之间的数字" maxlength="3" @blur="handUpdateSort(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column label="最后更新时间" :width="350" :show-overflow-tooltip="true" align="center">
              <template slot-scope="scope">
                <div>{{ scope.row.lastEditTime|parseTime }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" class-name="small-padding fixed-width" fixed="right" :width="400" align="left">
              <template slot-scope="scope">
                <template>
                  <el-link type="primary" @click="handUpdate(scope.row)">
                    修改
                  </el-link>
                </template>
                <template>
                  <el-link type="danger" @click="handDelete(scope.row)">
                    删除
                  </el-link>
                </template>
                <template>
                  <el-link type="primary" @click="handAdd(scope.row)">
                    添加子组织
                  </el-link>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </div>

      <!--------------- 新增或编辑的弹窗 模块 ----------------->
      <el-dialog
        :title="form.departmentId ? '编辑部门' : '新增部门'"
        :visible.sync="dialogFormVisible"
        :append-to-body="true"
        width="50%"
        :before-close="closeDialog"
      >
        <el-form ref="form" :model="form" :rules="rules">
          <el-form-item label="部门名称" :label-width="formLabelWidth" prop="name" required>
            <el-input v-model="form.name" autocomplete="off" placeholder="部门名称，最大20个字符" maxlength="20" show-word-limit />
          </el-form-item>
          <el-form-item label="上级部门" :label-width="formLabelWidth">
            <el-cascader
              v-model="form.pid"
              node-key="id"
              :options="sysDepartmentOptionList"
              :props="{ checkStrictly: true, expandTrigger: 'click', label: 'name', value: 'departmentId', emitPath: false }"
              :clearable="true"
              placeholder="请选择上级部门"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item label="排序" :label-width="formLabelWidth" prop="sort" required>
            <el-input v-model="form.sort" autocomplete="off" placeholder="数字范围为0~255，数字越小越靠前" maxlength="3" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-link type="info" @click="closeDialog()">取 消</el-link>
          <el-link type="primary" @click="handleSubmit()">确 定</el-link>
        </div>
      </el-dialog>

    </el-card>
  </div>
</template>
<script>

// api
import { updateDepartment, queryDepartmentList, delDepartment, queryDepartment } from '@/api/userAndRole/sysDepartment'

// 分页组件
// import Pagination from '@/components/Pagination'
// 水波纹插件注释
import waves from '@/directive/waves'

export default {
  name: 'SysDep',
  // components: { Pagination },
  directives: { waves },
  data() {
    return {
      activeIndex: '1',
      total: 0,
      list: [],
      listLoading: true,
      listQuery: {
        name: ''
      },
      // 表单信息
      form: {
        departmentId: '',
        pid: '0',
        name: '',
        sort: ''
      },
      // 弹窗显示隐藏
      dialogFormVisible: false,
      // 全部部门
      sysDepartmentOptionList: [],
      // 表单宽
      formLabelWidth: '100px',
      // 禁用选择上级部门
      isDisabled: false,
      // 规则验证
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ],
        sort: [
          { required: true, pattern: /^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])$/, message: '排序必须是0~255的数字', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.queryDepartmentList()
    this.queryDepartmentOptionList()
  },
  methods: {
    queryDepartmentList() {
      const curVue = this
      queryDepartmentList(this.listQuery).then(res => {
        if (res.code === 1) {
          curVue.listLoading = false
          curVue.list = res.data.sysDepartmentList
        } else {
          curVue.noticeUtil.errorMsg('组织获取失败！')
        }
      })
    },
    handUpdateSort(data) {
      const curVue = this
      updateDepartment({ departmentId: data.departmentId, sort: data.sort }).then(res => {
        if (res.code === 1) {
          curVue.noticeUtil.successMsg('操作成功！')
          curVue.listLoading = true
          curVue.queryDepartmentList()
          curVue.dialogFormVisible = false
        }
      })
    },
    handUpdate(data) {
      const curVue = this
      queryDepartment({ departmentId: data.departmentId }).then(res => {
        curVue.form = res.data
        curVue.dialogFormVisible = true

        curVue.queryDepartmentOptionList()
      })
    },
    handAdd(data) {
      this.queryDepartmentOptionList()
      if (data) {
        this.form.pid = data.departmentId
        this.isDisabled = true
      }

      this.dialogFormVisible = true
    },
    closeDialog() {
      console.log(11)
      const curVue = this
      curVue.form = {
        departmentId: '',
        pid: '0',
        name: '',
        sort: ''
      }
      curVue.dialogFormVisible = false
      curVue.listLoading = true
      curVue.queryDepartmentList()

      // 清空验证规则
      setTimeout(function() {
        if (curVue.$refs.form) {
          curVue.$refs.form.clearValidate()
          curVue.isDisabled = false
        }
      }, 1000)
    },
    load(tree, treeNode, resolve) {
      const curVue = this
      queryDepartmentList({ pid: tree.departmentId }).then(res => {
        if (res.code === 1) {
          resolve(res.data.sysDepartmentList)
        } else {
          curVue.noticeUtil.errorMsg('查询下级部门失败')
        }
      })
    },
    queryDepartmentOptionList() {
      const curVue = this
      queryDepartmentList({ multistep: true }).then(res => {
        if (res.code === 1) {
          // 内部类 不能选择本部门
          const departmentOptionList = function(data) {
            for (let i = 0; i < data.length; i++) {
              if (data[i].departmentId === curVue.form.departmentId) {
                data.splice(i, 1)
                return
              }

              if (data[i].children) {
                departmentOptionList(data[i].children)
              }
            }
          }

          // // 内部类 不能选择本部门子集
          // const departmentSonOptionList = function(data) {
          //   for (let i = 0; i < data.length; i++) {
          //     data[i].disabled = true
          //     departmentOptionList(data[i].children)
          //   }
          // }
          departmentOptionList(res.data.sysDepartmentList)
          this.sysDepartmentOptionList = res.data.sysDepartmentList
        } else {
          curVue.noticeUtil.errorMsg('获取部门失败')
        }
      })
    },
    handDelete(data) {
      const curVue = this
      this.noticeUtil.confirm('您确定要删除此部门吗?').then(() => {
        delDepartment({ departmentId: data.departmentId }).then(res => {
          if (res.code === 1) {
            curVue.noticeUtil.successMsg('操作成功！')
            curVue.listLoading = true
            curVue.queryDepartmentList()
          }
        })
      }).catch(() => {
        curVue.noticeUtil.warningMsg('已取消操作！')
      })
    },
    search() {
      this.queryDepartmentList()
    },
    handleSubmit() {
      const curVue = this
      curVue.isDisabled = false
      // 验证表单数据，合格时发送请求
      curVue.$refs.form.validate((valid, obj) => {
        if (valid) {
          updateDepartment(curVue.form).then(res => {
            if (res.code === 1) {
              curVue.noticeUtil.successMsg('操作成功！')
              curVue.listLoading = true
              curVue.queryDepartmentList()
              curVue.dialogFormVisible = false
              curVue.closeDialog()
            // eslint-disable-next-line no-empty
            } else {

            }
          })
        } else {
          curVue.noticeUtil.warningMsg('表单验证失败！')
        }
      })
    }
  }
}

</script>

<style lang="scss" scoped>
.search-bar{
  position: relative;
  z-index: 2;
  width: 100%;
  .base-condition{
    padding: 0 40px;
    background: #fff;
    box-shadow: 0 2px 4px 0 rgba(0,0,0,.14);
    .el-menu-demo,.el-menu-demo *{
      line-height: 50px;
      height: 50px;

      .el-menu-item{
        padding: 0 8px;
        margin-right: 20px;
      }
    }
  }
  .more-condition{
    position: absolute;
    top: 65px;
    background: #fff;
    width: 100%;
    height: auto;
    padding: 20px 40px;
    box-shadow: 0 2px 4px 0 rgba(0,0,0,.14);
  }
  .query-result{
    margin-top: 5px;
    font-size: 12px;
    color: #4c596e;
    padding: 15px 30px;
    background: #fbfdff;
  }
  .query-result *{
    line-height: 25px;
  }
  .filter-item{
    display: inline-block;
    padding: 0 10px;
    margin-left: 10px;
    border-radius: 12px;
    background: #e5e9f2;
    color: #7f8997;
  }
  .filter-item i{
    margin-left: 5px;
    font-weight: 700;
    cursor: pointer;
  }

}
.radius-input >>> input{
  border-radius: 100px !important;
}
</style>
<style scoped>
.radius-input >>> input{
      border-radius: 100px !important;
    }
</style>

